package com.micro.glszh.stat.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.micro.glszh.stat.base.HttpCodeEnum;
import com.micro.glszh.stat.domain.SysUser;
import com.micro.glszh.stat.exception.BadRequestException;
import com.micro.glszh.stat.exception.BusinessException;
import com.micro.glszh.stat.service.SysUserService;
import com.micro.glszh.stat.utils.JwtToken;
import com.micro.glszh.stat.utils.LocalUserUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.Optional;

/**
 * 权限拦截器
 *
 * @author hupeng
 * @date 2020-04-30
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService sysUserService;

    public PermissionInterceptor() {
        super();
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Optional<AuthCheck> authCheck = this.getAuthCheck(handler);
        if (!authCheck.isPresent()) {
            return true;
        }
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.isEmpty(bearerToken)) {
            throw new BusinessException(HttpCodeEnum.UNAUTHORIZED.getCode(), HttpCodeEnum.UNAUTHORIZED.getMessage());
        }

        if (!bearerToken.startsWith("Bearer")) {
            throw new BusinessException(HttpCodeEnum.UNAUTHORIZED.getCode(), HttpCodeEnum.UNAUTHORIZED.getMessage());
        }
        String[] tokens = bearerToken.split(" ");
        if (!(tokens.length == 2)) {
            throw new BusinessException(HttpCodeEnum.UNAUTHORIZED.getCode(), HttpCodeEnum.UNAUTHORIZED.getMessage());
        }
        String token = tokens[1];

        //检测用户是否被踢出
//        if (redisService.get(Constants.APP_LOGIN_USER + token) == null) {
//            throw new BusinessException(HttpCodeEnum.UNAUTHORIZED.getCode(), HttpCodeEnum.UNAUTHORIZED.getMessage());
//        }

        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        Map<String, Claim> map = optionalMap
                .orElseThrow(() -> new BadRequestException(HttpCodeEnum.UNAUTHORIZED));


        boolean valid = this.hasPermission(authCheck.get(), map);
        if (valid) {
            this.setToThreadLocal(map);
        }
        return valid;
    }

    private void setToThreadLocal(Map<String, Claim> map) {
        Integer uid = map.get("uid").asInt();
        Integer scope = map.get("scope").asInt();
        SysUser user = sysUserService.getById(uid);
        if (user == null) {
            throw new BusinessException(HttpCodeEnum.UNAUTHORIZED.getCode(), HttpCodeEnum.UNAUTHORIZED.getMessage());
        }
        LocalUserUtils.set(user, scope);
    }

    private boolean hasPermission(AuthCheck authCheck, Map<String, Claim> map) {
        Integer level = authCheck.value();
        Integer scope = map.get("scope").asInt();
        if (level < scope) {
            throw new BusinessException(HttpCodeEnum.UNAUTHORIZED.getCode(), HttpCodeEnum.UNAUTHORIZED.getMessage());
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LocalUserUtils.clear();
    }

    private Optional<AuthCheck> getAuthCheck(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AuthCheck authCheck = handlerMethod.getMethod().getAnnotation(AuthCheck.class);
            if (authCheck == null) {
                return Optional.empty();
            }
            return Optional.of(authCheck);
        }
        return Optional.empty();
    }

}
